package com.quanyan.stadium.service.commonComponent.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.common.utils.HttpUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.stadium.entity.vo.IMResponseGroupVo;
import com.quanyan.stadium.entity.vo.NearbyVo;
import com.quanyan.stadium.service.commonComponent.NearbyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Zheng.Ke
 * Date 2016/7/19.
 */
@Service("nearbyService")
public class NearbyServiceImpl implements NearbyService {
    private static Logger logger = LoggerFactory.getLogger(NearbyServiceImpl.class);
    @Value("${nearby.service.url}")
    private String nearbyServiceUrl;

    @Override
    public List<NearbyVo> findByPosition(double lat, double lng, int pageNo, int pageSize, int mnum) {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("ver", "2.0.0.0");
        paramsMap.put("protocol_ver", 1);
        paramsMap.put("lat", lat);
        paramsMap.put("lng", lng);
        paramsMap.put("pageNo", pageNo);
        paramsMap.put("pageSize", pageSize);
        paramsMap.put("mnum", mnum);

        String responStr = HttpUtils.sendWebRequestByPostJsonStr(null, nearbyServiceUrl, GsonUtils.toJson(paramsMap));
        List<NearbyVo> list = new ArrayList<NearbyVo>();
        IMResponseGroupVo vo = new IMResponseGroupVo();
        if (StringUtil.isBlankOrNull(responStr)) {
            logger.warn("调用附近的人接口出错。lat：{},lng：{},晌应：{}。", lat, lng, responStr);
            return null;
        }
        JSONObject jo = JSON.parseObject(responStr);
        if (jo.getInteger("errcode") != 200) {
            logger.warn("调用附近的人接口出错。lat：{},lng：{},晌应：{}。", lat, lng, responStr);
            return null;
        }
        JSONArray ja = jo.getJSONObject("data").getJSONArray("resultlist");
        for (int i=0; i<ja.size(); i++) {
            JSONObject jo1 = ja.getJSONObject(i);
            NearbyVo nearbyVo = new NearbyVo();
            nearbyVo.setUid(jo1.getInteger("uid"));
            nearbyVo.setDistance(jo1.getInteger("distance"));
            list.add(nearbyVo);
        }
        return list;
    }
}
